/**
 * 
 */
package com.gopay.bis.cmb.ebank.operation;

import java.math.BigDecimal;
import java.util.Date;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cmb.netpayment.Settle;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.cmb.ebank.pay.CmbB2cMessage;
import com.gopay.common.domain.bank.cmb.ebank.query.CmbB2cResMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.DateUtils;

/**
 * @CmbB2cHttpTransportImpl.java
 * @author Ryan
 * @2013-10-30 上午11:22:22 www.gopay.com.cn Inc.All rights reserved.
 */
public class CmbB2cQueryHelper {
	private static Logger logger = LoggerFactory.getLogger(CmbB2cQueryHelper.class);
	
    private Settle settle;
    private String cmbNetpayServer;
//    private byte[] LOCK = new byte[0];

    /***
     * 订单查询登录
     * @param branchId
     * @param coNo
     * @param pwd
     * @return 如果登录成功，返回true
     * @throws GopayException
     */
    public boolean login(String branchId, String coNo, String pwd)throws GopayException {
    	CmbB2cMessage message = new CmbB2cMessage();
    	message.setOutStlmCd(BankConstants.BANK_LOGO_CMB);
    	
        try {
//            synchronized (LOCK) {
            	boolean isInitOk=true;
//                settle = new Settle();
                int initOption = settle.SetOptions(cmbNetpayServer);
                // is success
                if (initOption == 0) {
                   
                } else {
                	String errorMsg = settle.GetLastErr(initOption);
                	isInitOk=false;
                	BankLogUtils.printB2cQueryErrorLog(message, errorMsg);
                    throw new GopayException(ProcCodeConstants.PROC_CODE_100E6037);
                }
                int isLogin = settle.LoginC(branchId, coNo, pwd);
                if (isLogin == 0) {
                } else {
                	String errorMsg=settle.GetLastErr(isLogin);
                	isInitOk=false;
                	BankLogUtils.printB2cQueryErrorLog(message, errorMsg);
                    throw new GopayException(ProcCodeConstants.PROC_CODE_100E6037);
                }
                return isInitOk;
//    		}
           
        } catch (Exception e) {
        	logger.error("登陆异常。。。。", e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6037);
        }
        
        
    }
    
    
  
    /**
     * 调用查询接口对订单进行查询，如果查询失败，则抛出异常
     * @param message
     * @return
     * @throws GopayException
     */
    public CmbB2cResMessage query(CmbB2cMessage message) throws GopayException {
        try {
            CmbB2cResMessage resMessage = new CmbB2cResMessage();
            StringBuffer result = new StringBuffer();
            BankLogUtils.printB2CQuerySendLog(message, ToStringBuilder.reflectionToString(message));
            int queryResult = settle.QuerySingleOrder(message.getDate(), message.getBillNo(), result);
            if(queryResult == 3){//未登陆
            	boolean login = login(message.getBranchID(), message.getCoNo(), message.getPrivatePwd());
            	logger.error(String.format("查询登陆结果：%s,商户号：%s", login, message.getCoNo()));
            	if(login){
            		queryResult = settle.QuerySingleOrder(message.getDate(), message.getBillNo(), result);
            		resMessage.setStrBuf(result);
            	}
            }else if(queryResult == 0){
            	resMessage.setStrBuf(result);
            }else {
                String errorMsg = settle.GetLastErr(queryResult);
                resMessage.setErrorMsg(errorMsg);
//                boolean login = login(message.getBranchID(), message.getCoNo(), message.getPrivatePwd());
//                logger.error(String.format("查询登陆结果：%s,商户号：%s,前查询结果：%s", login, message.getCoNo(), queryResult));
//                settle.Logout();
            }
            resMessage.setQueryResult(queryResult);
            BankLogUtils.printB2CQueryBlackLog(message, resMessage.getStrBuf());
            return resMessage;
        } catch (Exception e) {
        	logger.error("查询异常。。。。", e);
        	throw new GopayException(ProcCodeConstants.PROC_CODE_100E6037);
        }

    }

    /**
     * 转换查询到的订单结果信息 不用再判断msg是否为空，
     * 如果为空则会抛出异常 并捕获最后抛出GopayException异常
     * @param message
     * @param msg
     * @throws GopayException
     */
    public void parseToMessage(CmbB2cResMessage message, String msg) throws GopayException {
        try {
            // split the message to build CmbB2cResMessage instance
            String[] str = msg.split("\n");
            if (str != null && str.length > 3) {
                // 长度最小为4
                Date tranDate = null;
                if (str[0] != null && !"".equals(str[0])) {
                    tranDate = DateUtils.strToDate(str[0], "yyyyMMdd");
                    message.setTranDate(tranDate);
                }
                Date processDate = null;
                if (str[1] != null && !"".equals(str[1])) {
                    processDate = DateUtils.strToDate(str[1], "yyyyMMdd");
                    message.setProcessDate(processDate);
                }
                message.setOrderStatus(str[2]);
                message.setRetQueryMoney(new BigDecimal(str[3]));
            }
        } catch (Exception e) {
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6039);
        }
    }

    /**
     * @return the cmbNetpayServer
     */
    public String getCmbNetpayServer() {
        return cmbNetpayServer;
    }

    /**
     * @param cmbNetpayServer
     *            the cmbNetpayServer to set
     */
    public void setCmbNetpayServer(String cmbNetpayServer) {
        this.cmbNetpayServer = cmbNetpayServer;
    }
    
	public Settle getSettle() {
		return settle;
	}

	public void setSettle(Settle settle) {
		this.settle = settle;
		this.settle.SetOptions("payment.ebank.cmbchina.com");
	}

}
